package edu.sbcc.cs180.teamWon;

import java.io.*;
import java.net.*;
import java.util.*;

import org.w3c.dom.*;

import edu.sbcc.cs123.webutils.*;

import android.app.Activity;
import android.content.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

public class calendarActivity extends Activity implements OnClickListener, OnItemClickListener {
	CalendarAdapter calAdapter;
	CalendarListAdapter calListAdapter;
	private final String[] wkDay = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
	private final String[] months = { "January", "February", "March", "April", "May", "June", "July", "August",
			"September", "October", "November", "December" };
	private String addressStart = "https://www.google.com/calendar/feeds/";
	private String addressEnd = "/public/full?fields=entry(title,gd:when)&orderby=starttime&max-results=25&singleevents=true&sortorder=ascending&futureevents=true&start-min=2012-03-01T10:00:00.000-08:00&start-max=2012-12-31T23:59:00-08:00";
	private String[] addressGroup = { "/*****user account*****/ %40gmail.com" }; //Change to a single variable for the users account
	private String address = "https://www.google.com/calendar/feeds/ /***users account email****/%40gmail.com/public/full?fields=entry(title,gd:when)&orderby=starttime&max-results=25&singleevents=true&sortorder=ascending&futureevents=true&start-min=2012-03-01T10:00:00.000-08:00&start-max=2012-12-31T23:59:00-08:00";
	private String[] calendarEventList;
	private String[] mainEvntLst;
	private String[] meetEvntLst;
	private String[] sportEvntLst;
	private String dataSaved = "";
	private Button selectCal;
	private ImageView prevMonth;
	private ImageView nextMonth;
	private Calendar calendar;
	private GridView calGrid;
	private String longDate;
	private int month;
	private int curMonth;
	private int dayOfWeek;
	private int dayOfMonth;
	private int year;
	private int curYear;
	private ListView eventList;
	private int showCals;
	private long curDate;
	private long lastUpdate;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		calendar = Calendar.getInstance(Locale.getDefault());
		curDate = (calendar.getTimeInMillis()) / 10000;

		SharedPreferences settings = getSharedPreferences("CalData", 0);
		long lstUpDt = settings.getLong("lastUpdate", 0);
		String data = settings.getString("svdData", null);
		int setCal = settings.getInt("setCal", 0);
		if (lstUpDt == 0)
			lastUpdate = curDate;
		if (setCal > 1) {
			showCals = setCal;
		} else {
			showCals = 1;
		}
		if (data != null) {
			dataSaved = data;
		}
		if ((dataSaved.length() > 0) && (curDate > (lastUpdate + 120960))) {
			calendarEventList = dataSaved.split("/xx/");
			try {
				updateView();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				new UpdateViewAsyncTask().execute(address);
			} catch (Throwable e) {
				Log.e("Calendar", e.getMessage());// edit this
			}
			if (calendarEventList != null) {
				for (int i = 0; i < calendarEventList.length; i++) {
					dataSaved = dataSaved + (calendarEventList[i] + "/xx/");
				}
			}
		}
	}

	private void setAddress() {
		int tmpAdd = showCals;
		if (tmpAdd >= 4) {
			tmpAdd -= 4;
			address = addressStart + addressGroup[2] + addressEnd;
			new UpdateViewAsyncTask().execute(address);
			for (int i = 0; i < calendarEventList.length; i++) {
				meetEvntLst[i] = calendarEventList[i];
			}
			setSavedFile(2);
		}
		if (tmpAdd >= 2) {
			tmpAdd -= 2;
			address = addressStart + addressGroup[1] + addressEnd;
			new UpdateViewAsyncTask().execute(address);
			for (int i = 0; i < calendarEventList.length; i++) {
				sportEvntLst[i] = calendarEventList[i];
			}
			setSavedFile(1);
		}
		if (tmpAdd >= 1) {
			tmpAdd -= 1;
			address = addressStart + addressGroup[0] + addressEnd;
			new UpdateViewAsyncTask().execute(address);
			for (int i = 0; i < calendarEventList.length; i++) {
				mainEvntLst[i] = calendarEventList[i];
			}
			setSavedFile(0);
		}
	}
	private void setSavedFile(int calID){
		
	}

	@Override
	protected void onStop() {
		super.onStop();
		SharedPreferences settings = getSharedPreferences("CalData", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("setCal", showCals);
		editor.putString("svdData", dataSaved);
		editor.putLong("lastUpdate", lastUpdate);
		editor.commit();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean b = false;
		new MenuInflater(this).inflate(R.menu.optionsmenu, menu);
		b = super.onCreateOptionsMenu(menu);
		return b;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		boolean b = true;
		switch (item.getItemId()) {
		case R.id.menuAbout:
			Intent aboutIntent = new Intent(this, AboutActivity.class);
			startActivityForResult(aboutIntent, 0);
			break;
		case R.id.menuSetCal:
			Intent calIntent = new Intent(this, SettingsActivity.class);
			calIntent.putExtra("list", showCals);
			startActivityForResult(calIntent, 0);
			break;
		default:
			b = super.onOptionsItemSelected(item);
			break;
		}
		b = super.onOptionsItemSelected(item);
		return b;
	}

	private void setDate() {
		year = calendar.get(Calendar.YEAR);
		curYear = year;
		month = calendar.get(Calendar.MONTH);
		curMonth = month;
		dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
		dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		calendar.setTime(calendar.getTime());
	}

	private String setCalText() {
		String dateStr = wkDay[dayOfWeek - 1] + ", " + months[month] + " " + String.valueOf(dayOfMonth) + ", "
				+ String.valueOf(year);
		return dateStr;
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.prev_month_button:
			if (month == 0) {
				month = 11;
				year = year - 1;
			} else {
				month = month - 1;
			}
			calAdapter = new CalendarAdapter(this, month, year);
			calGrid.setAdapter(calAdapter);
			if ((month == curMonth) && (year == curYear)) {
				selectCal.setText(longDate);
			} else {
				selectCal.setText(months[month] + " " + year);
			}
			calAdapter.notifyDataSetChanged();
			break;
		case R.id.cal_select:
			if ((month != curMonth) || (year != curYear)) {
				month = curMonth;
				year = curYear;
				selectCal.setText(longDate);
			}
			calAdapter = new CalendarAdapter(this, month, year);
			calGrid.setAdapter(calAdapter);
			calAdapter.notifyDataSetChanged();
			break;
		case R.id.next_month_button:
			if (month == 11) {
				month = 0;
				year = year + 1;
			} else {
				month = month + 1;
			}
			calAdapter = new CalendarAdapter(this, month, year);
			calGrid.setAdapter(calAdapter);
			if ((month == curMonth) && (year == curYear)) {
				selectCal.setText(longDate);
			} else {
				selectCal.setText(months[month] + " " + year);
			}
			calAdapter.notifyDataSetChanged();
			break;
		default:
			return;
		}
	}

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		String testText = "You clicked something";
		Toast.makeText(this, testText, Toast.LENGTH_SHORT).show();

		// Intent intent = new Intent(this, CalendarAdapter.class);
		// intent.putExtra("position", position);
		// intent.putExtra("item", appAdapter.getItem(position));
		// startActivityForResult(intent, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			showCals = data.getExtras().getInt("list");
		}
	}

	private class UpdateViewAsyncTask extends AsyncTask<String, Integer, Exception> {
		private ProgressBar progBar;
		private TextView updateText;
		private Document document;

		@Override
		protected void onPreExecute() {
			setContentView(R.layout.mainlistlayout);
			progBar = (ProgressBar) findViewById(R.id.progressBar);
			updateText = (TextView) findViewById(R.id.progressTextView);
			updateText.setText("Updating...");
		}

		@Override
		protected Exception doInBackground(String... params) {
			progBar.setVisibility(ProgressBar.VISIBLE);
			String titles[] = new String[25];
			String[][] saveAry = new String[25][3];
			try {
				int i = 0;
				URL url = new URL(address);
				HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
				try {
					InputStream in = new BufferedInputStream(urlConnection.getInputStream());
					document = XmlUtil.getDocument(in);
					ArrayList<Node> nodes = XmlUtil.selectNodes(document, "/feed/entry");
					for (Node node : nodes) {
						NodeList evntChildren = node.getChildNodes();
						String evntName = evntChildren.item(0).getTextContent();
						Node evntTime = evntChildren.item(1);
						NamedNodeMap startStopTimes = evntTime.getAttributes();
						Node endTime = startStopTimes.item(0);
						Node startTime = startStopTimes.item(1);
						String endStr = endTime.getNodeValue();
						String startStr = startTime.getNodeValue();
						saveAry[i][0] = evntName;
						saveAry[i][1] = endStr;
						saveAry[i][2] = startStr;
						titles[i] = saveAry[i][0] + "/pp/" + saveAry[i][2] + "/pp/" + saveAry[i][1];
						i++;
					}
					i = 0;
					calendarEventList = titles;
				} finally {
					urlConnection.disconnect();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			updateText.setText("Updating " + values[0] + "%");
		}

		@Override
		protected void onPostExecute(Exception result) {
			try {
				if (result == null) {
					progBar.setVisibility(ProgressBar.GONE);
					updateView();
				} else
					Toast.makeText(calendarActivity.this, result.getMessage(), Toast.LENGTH_LONG).show();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void updateView() throws Exception {
		setContentView(R.layout.main);

		calendar = Calendar.getInstance(Locale.getDefault());

		calendar.setFirstDayOfWeek(0);
		setDate();
		longDate = setCalText();

		calendar = Calendar.getInstance(Locale.getDefault());

		prevMonth = (ImageView) findViewById(R.id.prev_month_button);
		prevMonth.setBackgroundResource(R.drawable.left_arrow_selector);
		prevMonth.setOnClickListener(this);

		selectCal = (Button) findViewById(R.id.cal_select);
		selectCal.setText(longDate);
		selectCal.setOnClickListener(this);

		nextMonth = (ImageView) findViewById(R.id.next_month_button);
		nextMonth.setBackgroundResource(R.drawable.right_arrow_selector);
		nextMonth.setOnClickListener(this);

		calAdapter = new CalendarAdapter(this, month, year);
		calListAdapter = new CalendarListAdapter(this, calendarEventList);

		calGrid = (GridView) findViewById(R.id.calGridView);
		calGrid.setAdapter(calAdapter);
		calGrid.setOnItemClickListener(this);

		eventList = (ListView) findViewById(R.id.eventListView);
		eventList.setAdapter(calListAdapter);
	}
}